package controller

import (
	"camera_app/entity"
	service "camera_app/repository"
	"camera_app/utils"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type UserController struct {
	UserRepo *service.UserRepository
}

func NewUserController(userRepo *service.UserRepository) *UserController {
	return &UserController{
		UserRepo: userRepo,
	}
}

func (u *UserController) GetUserHandler(context *gin.Context) {
	userId, exist := context.GetQuery("UserId")
	if !exist {
		utils.SetFailResponse(context, http.StatusBadRequest, "查询用户失败", nil)
	}
	if id, err := strconv.Atoi(userId); err == nil {
		user := &entity.User{UserId: id}
		user = u.UserRepo.GetOne(user)
		if user != nil {
			utils.SetSuccessResponse(context, user)
		} else {
			utils.SetSuccessResponse(context, nil)
		}

	} else {
		utils.SetFailResponse(context, http.StatusBadRequest, err.Error(), nil)
	}
}

func (u *UserController) LoginHandler(ctx *gin.Context) {
	{
		username, ex1 := ctx.GetPostForm("username")
		password, ex2 := ctx.GetPostForm("password")
		if !(ex1 && ex2) {
			ctx.JSON(http.StatusOK, gin.H{"msg": "error data received" + fmt.Sprint(ex1, ex2), "data": nil})
			return
		}
		user := &entity.User{
			Username: username,
			Password: password,
		}
		if uu, err := u.UserRepo.Login(user); err == nil {
			tokenString, _ := utils.GenerateToken(uu)
			ctx.JSON(http.StatusOK, gin.H{"msg": "success", "data": uu, "token": tokenString})
			fmt.Println(tokenString)
		} else {
			ctx.JSON(http.StatusOK, gin.H{"msg": "用户名或者密码错误 " + fmt.Sprint(err), "data": nil})
		}

	}
}
